package com.exonline.front.controller.shoppingcart;


import cn.hutool.core.util.IdUtil;
import com.exonline.commons.utils.TokenUtils;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @desc 购物车模块的C层
 * @author hbrj
 */
@WebServlet("/font/shoppingCart")
public class ShoppingServlet extends HttpServlet {
    // 使用Jackson库进行JSON格式的响应输出
    ObjectMapper mapper = new ObjectMapper();
    // 购物车类,用于处理购物车的相关业务逻辑
    ShoppingService service = new ShoppingService();

    /**
     * @desc  处理客户端发来的HTTP请求，依据请求中的method参数，调用不同的操作方法
     *        包括购物车的添加 删除  查询
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if ("add".equals(method)){
            this.add(req,resp);
        } else if ("delete".equals(method)) {
            this.delete(req,resp);
        } else if ("query".equals(method)) {
            this.query(req,resp);
        }

    }

    /**
     * @desc  1. 添加课程到购物车
     * @param req  客户端请求
     * @param resp 服务端响应
     */
    private void add(HttpServletRequest req, HttpServletResponse resp) {
        try {
            // 生成唯一的购物车ID
            String id = IdUtil.simpleUUID();
            // 从请求中获取学生ID
            String sid = TokenUtils.getId(req);
            if (sid == null) {
                Map<String, Object> map = new HashMap<>();
                map.put("code", 400);
                map.put("msg", "未能从请求中获取到学生ID，请检查相关设置");
                mapper.writeValue(resp.getWriter(), map);
                return;
            }
            // 从请求中获取课程ID
            String cid = req.getParameter("cid");
            if (cid == null) {
                Map<String, Object> map = new HashMap<>();
                map.put("code", 400);
                map.put("msg", "未能从请求中获取到课程ID，请检查前端参数传递");
                mapper.writeValue(resp.getWriter(), map);
                return;
            }

            // 调用Service层方法添加课程到购物车
            boolean result = service.addCourseToShoppingCart(id, sid, cid);
            Map<String, Object> resultMap = new HashMap<>();
            if (result) {
                resultMap.put("code", 200);
                resultMap.put("msg", "课程添加到购物车成功");
            } else {
                resultMap.put("code", 500);
                resultMap.put("msg", "课程添加到购物车失败，可能已存在该课程或出现数据库错误");
            }
            mapper.writeValue(resp.getWriter(), resultMap);
        } catch (IOException e) {
            e.printStackTrace();
            try {
                Map<String, Object> errorMap = new HashMap<>();
                errorMap.put("code", 500);
                errorMap.put("msg", "处理添加课程到购物车请求时出现错误");
                mapper.writeValue(resp.getWriter(), errorMap);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @desc  2. 删除课程 根据学生id和课程id
     * @param req  客户端请求
     * @param resp 服务端响应
     */
    private void delete(HttpServletRequest req, HttpServletResponse resp) {
        try {
            // 从请求中获取学生ID
            String sid = TokenUtils.getId(req);
            if (sid == null) {
                Map<String, Object> map = new HashMap<>();
                map.put("code", 400);
                map.put("msg", "未能从请求中获取到学生ID，请检查相关设置");
                mapper.writeValue(resp.getWriter(), map);
                return;
            }
            // 从请求中获取课程ID
            String cid = req.getParameter("cid");
            if (cid == null) {
                Map<String, Object> map = new HashMap<>();
                map.put("code", 400);
                map.put("msg", "未能从请求中获取到课程ID，请检查前端参数传递");
                mapper.writeValue(resp.getWriter(), map);
                return;
            }
            // 调用Service层方法删除课程
            boolean result = service.deleteCourseFromShoppingCart(sid, cid);
            Map<String, Object> resultMap = new HashMap<>();
            if (result) {
                resultMap.put("code", 200);
                resultMap.put("msg", "课程从购物车删除成功");
            } else {
                resultMap.put("code", 500);
                resultMap.put("msg", "课程从购物车删除失败，可能课程不存在或出现数据库错误");
            }
            mapper.writeValue(resp.getWriter(), resultMap);
        } catch (IOException e) {
            e.printStackTrace();
            try {
                Map<String, Object> errorMap = new HashMap<>();
                errorMap.put("code", 500);
                errorMap.put("msg", "处理删除课程从购物车请求时出现错误");
                mapper.writeValue(resp.getWriter(), errorMap);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
    /**
     * @desc  3. 查询课程
     * @param req
     * @param resp
     */
    private void query(HttpServletRequest req, HttpServletResponse resp) {
        try {
            // 从Session中获取学生ID
            String sid = TokenUtils.getId(req);
            if (sid == null) {
                Map<String, Object> map = new HashMap<>();
                map.put("code", 400);
                map.put("msg", "未能从Session中获取到学生ID，请检查相关设置");
                mapper.writeValue(resp.getWriter(), map);
                return;
            }
            // 调用Service层方法查询购物车课程信息
            List<Map<String, Object>> courses = service.queryShoppingCartCourses(sid);
            Map<String, Object> resultMap = new HashMap<>();
            if (courses!= null &&!courses.isEmpty()) {
                resultMap.put("code", 200);
                resultMap.put("msg", "购物车课程查询成功");
                resultMap.put("data", courses);
            } else {
                resultMap.put("code", 400);
                resultMap.put("msg", "购物车暂无课程或查询出现问题");
                resultMap.put("data", null);
            }
            mapper.writeValue(resp.getWriter(), resultMap);
        } catch (IOException e) {
            e.printStackTrace();
            try {
                Map<String, Object> errorMap = new HashMap<>();
                errorMap.put("code", 500);
                errorMap.put("msg", "处理购物车课程查询请求时出现错误");
                mapper.writeValue(resp.getWriter(), errorMap);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}


